<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI智能助手</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .chat-container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            width: 100%;
            max-width: 1000px;
            height: 80vh;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .chat-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px 30px;
            text-align: center;
        }

        .chat-header h1 {
            font-size: 1.8em;
            margin-bottom: 5px;
        }

        .chat-header p {
            opacity: 0.9;
            font-size: 0.9em;
        }

        .chat-messages {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            background: #f8f9fa;
        }

        .message {
            margin-bottom: 20px;
            display: flex;
            align-items: flex-start;
            gap: 12px;
        }

        .message.user {
            flex-direction: row-reverse;
        }

        .message-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            color: white;
            flex-shrink: 0;
        }

        .message.user .message-avatar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }

        .message.ai .message-avatar {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }

        .message-content {
            max-width: 70%;
            padding: 15px 20px;
            border-radius: 18px;
            position: relative;
            word-wrap: break-word;
            line-height: 1.5;
            white-space: pre-wrap;
        }

        .message.user .message-content {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-bottom-right-radius: 5px;
        }

        .message.ai .message-content {
            background: white;
            color: #333;
            border: 1px solid #e1e5e9;
            border-bottom-left-radius: 5px;
        }

        .message-time {
            font-size: 0.75em;
            opacity: 0.7;
            margin-top: 5px;
            text-align: right;
        }

        .message.user .message-time {
            text-align: left;
        }

        .chat-input-container {
            padding: 20px;
            background: white;
            border-top: 1px solid #e1e5e9;
        }

        .chat-input-form {
            display: flex;
            gap: 15px;
            align-items: flex-end;
        }

        .input-group {
            flex: 1;
            position: relative;
        }

        .chat-input {
            width: 100%;
            padding: 15px 20px;
            border: 2px solid #e1e5e9;
            border-radius: 25px;
            font-size: 16px;
            resize: none;
            outline: none;
            transition: all 0.3s ease;
            min-height: 50px;
            max-height: 120px;
        }

        .chat-input:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .send-btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 15px 25px;
            border-radius: 25px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            flex-shrink: 0;
            height: 50px;
            width: 150px;
        }

        .send-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
        }

        .send-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .typing-indicator {
            display: none;
            align-items: center;
            gap: 8px;
            padding: 15px 20px;
            background: white;
            border-radius: 18px;
            border: 1px solid #e1e5e9;
            max-width: 70%;
            margin-bottom: 20px;
        }

        .typing-dots {
            display: flex;
            gap: 4px;
        }

        .typing-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: #667eea;
            animation: typing 1.4s infinite ease-in-out;
        }

        .typing-dot:nth-child(1) { animation-delay: -0.32s; }
        .typing-dot:nth-child(2) { animation-delay: -0.16s; }

        @keyframes typing {
            0%, 80%, 100% {
                transform: scale(0.8);
                opacity: 0.5;
            }
            40% {
                transform: scale(1);
                opacity: 1;
            }
        }

        .settings-panel {
            background: white;
            border-top: 1px solid #e1e5e9;
            padding: 15px 20px;
            display: none;
        }

        .settings-row {
            display: flex;
            gap: 20px;
            align-items: center;
            margin-bottom: 10px;
        }

        .settings-label {
            font-weight: 600;
            color: #555;
            min-width: 80px;
        }

        .settings-input {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }

        .toggle-settings {
            background: none;
            border: none;
            color: #667eea;
            cursor: pointer;
            font-size: 14px;
            padding: 5px 10px;
            border-radius: 5px;
            transition: background 0.3s ease;
        }

        .toggle-settings:hover {
            background: #f0f2ff;
        }

        .clear-chat {
            background: #dc3545;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            transition: background 0.3s ease;
        }

        .clear-chat:hover {
            background: #c82333;
        }

        .test-stream-btn {
            background: #28a745;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            transition: background 0.3s ease;
        }

        .test-stream-btn:hover {
            background: #218838;
        }

        .welcome-message {
            text-align: center;
            color: #666;
            margin: 40px 0;
        }

        .welcome-message h3 {
            color: #333;
            margin-bottom: 10px;
        }

        .suggestions {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            justify-content: center;
            margin-top: 20px;
        }

        .suggestion-btn {
            background: white;
            border: 1px solid #e1e5e9;
            padding: 8px 15px;
            border-radius: 20px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .suggestion-btn:hover {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }

        @media (max-width: 768px) {
            .chat-container {
                height: 90vh;
                border-radius: 0;
            }
            
            .message-content {
                max-width: 85%;
            }
            
            .chat-input-form {
                flex-direction: column;
                gap: 10px;
            }
            
            .send-btn {
                align-self: flex-end;
            }
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <div class="chat-header">
            <h1>🤖 AI智能助手</h1>
            <p>基于阿里云通义千问，为您提供智能对话服务</p>
        </div>

        <div class="chat-messages" id="chatMessages">
            <div class="welcome-message">
                <h3>👋 欢迎使用AI智能助手</h3>
                <p>我可以帮助您回答问题、编写代码、分析数据等</p>
                <div class="suggestions">
                    <button class="suggestion-btn" onclick="sendSuggestion('你好，请介绍一下你自己')">自我介绍</button>
                    <button class="suggestion-btn" onclick="sendSuggestion('帮我写一个Java Hello World程序')">编程帮助</button>
                    <button class="suggestion-btn" onclick="sendSuggestion('解释一下什么是人工智能')">知识问答</button>
                    <button class="suggestion-btn" onclick="sendSuggestion('给我讲个笑话')">娱乐放松</button>
                </div>
            </div>
        </div>

        <div class="typing-indicator" id="typingIndicator">
            <div class="message-avatar" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">AI</div>
            <div class="typing-dots">
                <div class="typing-dot"></div>
                <div class="typing-dot"></div>
                <div class="typing-dot"></div>
            </div>
            <span>AI正在思考...</span>
        </div>

        <div class="settings-panel" id="settingsPanel">
            <div class="settings-row">
                <span class="settings-label">多样性:</span>
                <input type="range" id="temperature" min="0" max="20" value="7" class="settings-input">
                <span id="temperatureValue">0.7</span>
            </div>
            <div class="settings-row">
                <span class="settings-label">最大长度:</span>
                <input type="number" id="maxTokens" value="2048" min="100" max="4096" class="settings-input">
            </div>
            <div class="settings-row">
                <span class="settings-label">流式模式:</span>
                <input type="checkbox" id="streamMode" class="settings-input" style="width: auto;" checked>
                <span style="font-size: 12px; color: #666;">启用流式回复，实时显示AI回复过程</span>
            </div>
        </div>

        <div class="chat-input-container">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                <button class="toggle-settings" onclick="toggleSettings()">⚙️ 设置</button>
                <div style="display: flex; gap: 10px;">
                    <button class="clear-chat" onclick="clearChat()">🗑️ 清空对话</button>
                    <a href="/api/tts/page" class="clear-chat" style="text-decoration: none; display: inline-block; line-height: 24px;">🎤 语音合成</a>
                </div>
            </div>
            <form class="chat-input-form" id="chatForm">
                <div class="input-group">
                    <textarea 
                        id="messageInput" 
                        class="chat-input" 
                        placeholder="输入您的消息..."
                        rows="1"
                        required
                    ></textarea>
                </div>
                <button type="submit" class="send-btn" id="sendBtn">
                    发送
                </button>
            </form>
        </div>
    </div>

    <script>
        let chatHistory = [];
        let isTyping = false;
        let currentStreamingMessage = null;

        // 自动调整输入框高度
        const messageInput = document.getElementById('messageInput');
        messageInput.addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = Math.min(this.scrollHeight, 120) + 'px';
        });

        // 处理表单提交
        document.getElementById('chatForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            await sendMessage();
        });

        // 发送消息
        async function sendMessage() {
            const input = document.getElementById('messageInput');
            const message = input.value.trim();
            
            if (!message || isTyping) return;

            // 添加用户消息到界面
            addMessage(message, 'user');
            
            // 清空输入框
            input.value = '';
            input.style.height = 'auto';
            
            // 检查是否启用流式模式
            const streamMode = document.getElementById('streamMode').checked;
            
            if (streamMode) {
                // 流式模式：实时显示AI回复
                await sendStreamMessage(message);
            } else {
                // 同步模式：等待完整回复
                await sendSyncMessage(message);
            }
        }

        // 发送同步消息
        async function sendSyncMessage(message) {
            // 显示AI正在输入
            showTypingIndicator();
            
            try {
                // 构建请求数据
                const requestData = {
                    prompt: message,
                    history: chatHistory,
                    temperature: parseFloat(document.getElementById('temperatureValue').textContent),
                    maxTokens: parseInt(document.getElementById('maxTokens').value),
                    streamMode: false
                };

                const response = await fetch('/api/ai/chat', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestData)
                });

                const result = await response.json();

                if (result.success) {
                    // 添加AI回复到界面
                    addMessage(result.response, 'ai');
                    
                    // 更新聊天历史
                    chatHistory.push({
                        role: 'user',
                        content: message
                    });
                    chatHistory.push({
                        role: 'assistant',
                        content: result.response
                    });
                } else {
                    addMessage('抱歉，我遇到了一些问题：' + result.errorMessage, 'ai');
                }
            } catch (error) {
                addMessage('抱歉，网络连接出现问题，请稍后重试。', 'ai');
            } finally {
                hideTypingIndicator();
            }
        }

        // 发送流式消息
        async function sendStreamMessage(message) {
            showTypingIndicator(); // 显示"正在输入"
            let fullResponse = '';
            
            try {
                const requestData = {
                    prompt: message,
                    history: chatHistory,
                    temperature: parseFloat(document.getElementById('temperatureValue').textContent),
                    maxTokens: parseInt(document.getElementById('maxTokens').value),
                    streamMode: true
                };

                currentStreamingMessage = addMessage('正在思考...', 'ai');
                
                const response = await fetch('/api/ai/chat/stream', {
                    method: 'POST',
                    headers: { 
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestData)
                });

                if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let buffer = '';
                let eventCount = 0;
                
                while (true) {
                    const { done, value } = await reader.read();
                    if (done) {
                        break;
                    }
                    
                    const chunk = decoder.decode(value, { stream: true });
                    buffer += chunk;
                    
                    // 按双换行符分割SSE事件
                    const events = buffer.split('\n\n');
                    buffer = events.pop() || ''; // 保留最后一个不完整的事件
                    
                    for (const event of events) {
                        if (!event.trim()) continue;
                        
                        eventCount++;
                        
                        let eventType = '';
                        let eventData = '';
                        
                        // 解析事件类型和数据
                        const lines = event.split('\n');
                        for (const line of lines) {
                            if (line.startsWith('event: ')) {
                                eventType = line.slice(7).trim();
                            } else if (line.startsWith('data: ')) {
                                eventData = line.slice(6).trim();
                            }
                        }
                        
                        // 处理text事件
                        if (eventType === 'text' && eventData) {
                            try {
                                const parsedData = JSON.parse(eventData);
                                if (parsedData.text) {
                                    fullResponse += parsedData.text;
                                    // 分段渲染
                                    if (currentStreamingMessage) {
                                        const paragraphs = fullResponse.split(/\n{2,}|\r\n{2,}/);
                                        currentStreamingMessage.innerHTML = paragraphs.map(p => `<p>${p.replace(/\n/g, '<br>')}</p>`).join('');
                                        const messagesContainer = document.getElementById('chatMessages');
                                        messagesContainer.scrollTop = messagesContainer.scrollHeight;
                                    }
                                }
                            } catch (e) {
                                console.warn('Failed to parse SSE text data:', eventData, e);
                            }
                        }
                        // 处理complete事件
                        else if (eventType === 'complete') {
                        }
                        // 处理error事件
                        else if (eventType === 'error') {
                            try {
                                if (currentStreamingMessage) {
                                    currentStreamingMessage.textContent = '错误: ' + eventData;
                                }
                            } catch (e) {
                                console.error('Failed to parse error data:', eventData, e);
                            }
                        }
                        // 处理没有事件类型的data行
                        else if (!eventType && eventData) {
                            try {
                                const parsedData = JSON.parse(eventData);
                                if (parsedData.text) {
                                    fullResponse += parsedData.text;
                                    
                                    // 更新DOM元素 - 直接更新整个消息元素，与测试页面保持一致
                                    if (currentStreamingMessage) {
                                        currentStreamingMessage.textContent = fullResponse;
                                        
                                        // 滚动到底部
                                        const messagesContainer = document.getElementById('chatMessages');
                                        messagesContainer.scrollTop = messagesContainer.scrollHeight;
                                    }
                                }
                            } catch (e) {
                                console.warn('Failed to parse data without event type:', eventData, e);
                            }
                        }
                    }
                }
                
            } catch (error) {
                if (currentStreamingMessage) {
                    currentStreamingMessage.textContent = '抱歉，网络连接出现问题，请稍后重试。';
                }
            } finally {
                if (fullResponse) {
                    chatHistory.push({ role: 'user', content: message });
                    chatHistory.push({ role: 'assistant', content: fullResponse });
                }
                currentStreamingMessage = null;
                hideTypingIndicator(); // 隐藏"正在输入"
            }
        }

        // 添加消息到界面
        function addMessage(content, sender) {
            const messagesContainer = document.getElementById('chatMessages');
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message ' + sender;

            // 头像
            const avatarDiv = document.createElement('div');
            avatarDiv.className = 'message-avatar';
            avatarDiv.textContent = sender === 'user' ? '我' : 'AI';
            messageDiv.appendChild(avatarDiv);

            // 内容
            const contentDiv = document.createElement('div');
            contentDiv.className = 'message-content';
            if (sender === 'ai') {
                // 分段渲染
                const paragraphs = content.split(/\n{2,}|\r\n{2,}/);
                contentDiv.innerHTML = paragraphs.map(p => `<p>${p.replace(/\n/g, '<br>')}</p>`).join('');
            } else {
                contentDiv.textContent = content;
            }
            messageDiv.appendChild(contentDiv);

            // 时间（可选）
            const messageTime = document.createElement('div');
            messageTime.className = 'message-time';
            messageTime.textContent = new Date().toLocaleTimeString();
            messageDiv.appendChild(messageTime);

            messagesContainer.appendChild(messageDiv);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
            return contentDiv;
        }

        // 显示输入指示器
        function showTypingIndicator() {
            isTyping = true;
            document.getElementById('typingIndicator').style.display = 'flex';
            document.getElementById('sendBtn').disabled = true;
            document.getElementById('chatMessages').scrollTop = document.getElementById('chatMessages').scrollHeight;
        }

        // 隐藏输入指示器
        function hideTypingIndicator() {
            isTyping = false;
            document.getElementById('typingIndicator').style.display = 'none';
            document.getElementById('sendBtn').disabled = false;
        }

        // 发送建议消息
        function sendSuggestion(text) {
            document.getElementById('messageInput').value = text;
            sendMessage();
        }

        // 切换设置面板
        function toggleSettings() {
            const panel = document.getElementById('settingsPanel');
            panel.style.display = panel.style.display === 'none' ? 'block' : 'none';
        }

        // 清空对话
        function clearChat() {
            if (confirm('确定要清空所有对话记录吗？')) {
                chatHistory = [];
                document.getElementById('chatMessages').innerHTML = `
                    <div class="welcome-message">
                        <h3>👋 欢迎使用AI智能助手</h3>
                        <p>我可以帮助您回答问题、编写代码、分析数据等</p>
                        <div class="suggestions">
                            <button class="suggestion-btn" onclick="sendSuggestion('你好，请介绍一下你自己')">自我介绍</button>
                            <button class="suggestion-btn" onclick="sendSuggestion('帮我写一个Java Hello World程序')">编程帮助</button>
                            <button class="suggestion-btn" onclick="sendSuggestion('解释一下什么是人工智能')">知识问答</button>
                            <button class="suggestion-btn" onclick="sendSuggestion('给我讲个笑话')">娱乐放松</button>
                        </div>
                    </div>
                `;
            }
        }

        // 温度滑块事件
        document.getElementById('temperature').addEventListener('input', function() {
            document.getElementById('temperatureValue').textContent = (this.value / 10).toFixed(1);
        });

        // 回车发送消息（Shift+Enter换行）
        messageInput.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });
    </script>
</body>
</html>